package cn.danger.com.fragment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Handler;

import java.util.ArrayList;
import java.util.List;

import cn.danger.com.activity.MainActivity;
import cn.danger.com.fragment.calender.CalendarFragment;
import cn.danger.com.fragment.memo.MemoFragment;
import cn.danger.com.fragment.schedule.ScheduleFragment;
import cn.danger.com.fragment.user.UserFragment;

/**
 * Created by 俊 on 2016/12/26.
 */
public class FragmentController {

    private static FragmentController controller;
    private int containerId;
    private FragmentManager manager;
    private List<Fragment> fragments;
    private Handler handler;

    private FragmentController(MainActivity activity, int containerId, Handler handler) {

        manager = activity.getFragmentManager();
        this.containerId = containerId;
        this.handler = handler;

        initFragment();

    }

    public static FragmentController getInstance(MainActivity activity, int containerId, Handler handler) {
        if (controller == null) {
            synchronized (FragmentController.class) {
                if (controller == null) {
                    controller = new FragmentController(activity, containerId, handler);
                }
            }
        }
        return controller;
    }

    private void initFragment() {
        fragments = new ArrayList<>();
        fragments.add(new ScheduleFragment());
        fragments.add(new MemoFragment());
        fragments.add(new CalendarFragment());
        UserFragment userFragment = new UserFragment();
        userFragment.setHandler(handler);
        fragments.add(userFragment);

        FragmentTransaction transaction = manager.beginTransaction();

        for (Fragment fragment : fragments) {
            transaction.add(containerId, fragment);
        }
        transaction.commit();
    }

    private void hideFragments() {
        FragmentTransaction transaction = manager.beginTransaction();
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                transaction.hide(fragment);
            }
        }
        transaction.commit();
    }

    public void showFragment(int position) {
        hideFragments();
        Fragment fragment = fragments.get(position);
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.show(fragment);
        transaction.commit();
    }

    public Fragment getFragment(int position) {
        return fragments.get(position);
    }

}
